package messwertrechner;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Contains a set of measurements.
 *
 * @author Benedikt Markt
 *
 */
public class DataContainer {
	private List<Data> dataList;
	private int dataNumber;
	
	/**
	 * Default Constructor
	 *
	 * @author Benedikt Markt
	 * 
	 * @param dataIndex Index of the instrument that was read
	 *
	 */
	public DataContainer(int dataIndex) {
		this.dataList = new LinkedList<Data>();
		this.dataNumber = dataIndex;
	}
	
	/**
	 * Adds a data point to the list
	 * 
	 * @author Benedikt Markt
	 *
	 * @param data the data point to add
	 */
	public void add(Data data) {
		this.dataList.add(data);
	}
	
	/**
	 * Converts a string to a Data object and adds it to the list
	 *
	 * @author Benedikt Markt
	 *
	 * @param data the string to add
	 */
	public void addString(String data) {
		String sepData[] = data.split("\\t");
		int time = Integer.parseInt(sepData[0]);
		Double value = Double.parseDouble(sepData[1].replace(',', '.'));
		this.add(new Data(time, value));
	}
	
	/**
	 * Zeroes the values from the first measurement
	 * @author Benedikt Markt
	 *
	 */
	public void zero() {
		if(!this.dataList.isEmpty()) {
			Data first = this.dataList.get(0);
			Double valueShift = first.getValue();
			for(Data d: this.dataList) {
				d.setValue(d.getValue()-valueShift);
			}
		}
	}

	/**
	 * Prints the contents of the DataContainer to stdio
	 * 
	 * @author Benedikt Markt
	 *
	 */
	public void print() {
		for(Data d: this.dataList) {
			System.out.println("Time: " + d.getTime() + "s \t Value: " + d.getValue());
		}
		
	}
	
	/**
	 * Exports the contents of DataContainer to an Excel file
	 *
	 * @author Benedikt Markt
	 *
	 * @param fileName name of the file to export to
	 */
	public void writeToExcel(String fileName) {
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(new File(fileName));
			WritableSheet sheet = workbook.createSheet("Datensatz " + this.dataNumber, 0);
			Label timeLabel = new Label (0, 0, "Zeit");
			Label valueLabel = new Label (1, 0, "Messwert");
			sheet.addCell(timeLabel);
			sheet.addCell(valueLabel);
			int i = 1;
			for(Data d: this.dataList) {
				Number timeNum = new Number(0, i, d.getTime());
				Number valueNum = new Number(1, i, d.getValue());
				sheet.addCell(timeNum);
				sheet.addCell(valueNum);
				i++;
			}
			workbook.write();
			workbook.close();
		} catch (IOException | WriteException e) {
			System.out.println("Excel Datei kann nicht erstellt werden");
		}
		
	}

}
